package net.sppan.blog.store;

import net.sppan.blog.model.User;
import net.sppan.blog.utils.ObjectUtils;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserStore {

	private UserStore() {

	}

	public static final UserStore instance = new UserStore();
	private Map<String, User> idMapping = new HashMap<>();
	private Map<String, String> parentMapping = new HashMap<>();

	public void init() {
		List<User> users = User.dao.getAllList();
		if (ObjectUtils.isNotEmpty(users)) {
			Map<String, String> _parentMapping = new HashMap<>();
			Map<String, User> _idMapping = new HashMap<>();
			for (User user : users) {
				Integer parent = user.getParent();
				_idMapping.put(user.getId().toString(), user);
				if (parent != null) {
					_parentMapping.put(user.getId().toString(), parent.toString());
				}
			}
			idMapping = _idMapping;
			parentMapping = _parentMapping;
		}
	}

	public String getParentName(String userId) {
		String parentId = parentMapping.get(userId);
		if (StringUtils.isNotEmpty(parentId) && idMapping.get(parentId) != null) {
			return idMapping.get(parentId).getId().toString();
		}
		return "";
	}

	public String getUserName(String userId) {
		User u = idMapping.get(userId);
		if (u != null) {
			return u.getName();
		}
		return "";
	}

	public Integer getUserThreshold(String userId) {
		User u = idMapping.get(userId);
		if (u != null) {
			return u.getClickNumLimit();
		}
		return 0;
	}

	public String getParentId(String userId) {
		return parentMapping.get(userId);
	}
	public String getAccountById(String userId){
		User u = idMapping.get(userId);
		if (u != null) {
			return u.getAccount();
		}
		return "";
	}


}
